import { getSheetDetail, saveSheet } from '@/services/commonService';
import { RootDispatch } from '@/store';
import { Button } from 'antd';
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { DY_FEILD_KEY, TABLE_PROPS_KEY } from '@/consts';
import { leftDatas } from '../../datas';
import ExportExcelFileBtn from './ExportExcelFileBtn';
import ExportPdfBtn from './ExportPdfBtn';
import styles from './index.module.less';
import { Celldata, CellDataMap } from '../../types';
import { isField } from './utils';

const { luckysheet } = window;

interface HandleCellDataRes {
  isLoop: boolean;
  endArrIndex?: number;
}

interface HandleCellDataOptions {
  cellData: Celldata[];
  startArrIndex: number;
}

interface InsetRowsOptions {
  rowNumber: number;
  rowDataArr: Celldata[];
  resolve;
  endArrIndex: number;
}

const Header = () => {
  const distpatch = useDispatch<RootDispatch>();

  // 更新表格数据
  const onUpdata = async (startArrIndex: number = 0) => {
    const sheetsData = luckysheet.getAllSheets();
    console.log('更新', sheetsData[0].celldata);

    const { isLoop, endArrIndex } = await handleCellData({
      cellData: sheetsData[0].celldata,
      startArrIndex,
    });
    console.log('最后结果处理', isLoop);
    if (isLoop) {
      onUpdata(endArrIndex);
    }
  };

  // 填充表格数据
  const handleCellData = (data: HandleCellDataOptions): Promise<HandleCellDataRes> => {
    const { cellData, startArrIndex } = data;
    return new Promise((resolve) => {
      const cellDataMap: CellDataMap = new Map();
      let endArrIndex = startArrIndex;
      // const dataMap = {};
      // // 左侧数据字典
      // leftDatas.forEach((item) => {
      //   dataMap[item.title] = item.[TABLE_PROPS_KEY].table;
      // });

      // 批量处理表单内容，转成对象
      for (let i = startArrIndex; i < cellData.length; i++) {
        const item = cellData[i];
        // 获取接口需要参数
        // if (dataMap[key]) {
        // }
        if (!isField(item)) continue;
        // 取单row数据处理
        if (cellDataMap.has(item.r) || cellDataMap.size === 0) {
          if (!cellDataMap.has(item.r)) cellDataMap.set(item.r, []);
          const cellItem = cellDataMap.get(item.r);
          cellItem?.push(item);
          console.log('cellItem', cellItem);

          cellDataMap.set(item.r, cellItem || []);
          endArrIndex = i;
        }
      }
      if (cellDataMap.size === 0) {
        resolve({
          isLoop: false,
        });
        return;
      }
      const [rowNumber, rowDataArr] = cellDataMap.entries().next().value;
      console.log('k', rowDataArr, rowNumber);
      insetRows({ rowNumber, rowDataArr, resolve, endArrIndex });
    });
  };

  /** 表格添加单行数据 */
  const insetRows = (data: InsetRowsOptions) => {
    const { rowNumber, rowDataArr, resolve, endArrIndex } = data;
    let addRowNumber = 0;
    // 计算最大插入row数量
    rowDataArr.forEach((rowItem) => {
      const len = rowItem?.v.v?.[TABLE_PROPS_KEY]?.[DY_FEILD_KEY].length || 0;
      if (len && len > addRowNumber) {
        addRowNumber = len;
      }
    });
    console.log('addRowNumber', addRowNumber);

    // 插入配置
    const type = 'row'; // row column
    const start_index = rowNumber || 0;
    const options = {
      // 修正插入行，本身行也需要替换，所以减1
      number: addRowNumber,
      // number: addRowNumber > 0 ? addRowNumber - 1 : 0,
      success: () => {
        // 读取row需要的接口数据

        // 添加数据
        addRowsData(rowDataArr, resolve, endArrIndex);
      },
    };
    luckysheet.insertRowBottomOrColumnRight(type, start_index, options);
    // 重置选区高亮
    luckysheet.setRangeShow(
      { row: [0, 0], column: [0, 0] },
      {
        show: false,
      },
    );
  };

  // 填充数据
  const addRowsData = (cellItem: Celldata[], resolve, endArrIndex) => {
    cellItem.forEach(({ v, r, c }) => {
      // 获取表格value值，或是请求数据
      const dataArr = v.v?.[TABLE_PROPS_KEY]?.[DY_FEILD_KEY] || [];
      dataArr?.forEach((item, index) => {
        luckysheet.setCellValue(r + index, c, {
          m: item,
          ct: {
            fa: 'General',
            t: 'g',
          },
          v: item,
        });
      });
    });

    resolve({
      isLoop: true,
      endArrIndex,
    });
  };

  const onClickPreView = () => {
    distpatch.printReport.updateLucksheetOptions({
      showtoolbar: false,
    });
  };

  // 只读模式返回后端转换
  const readeGetSheetData = () => {
    const sheetfile = luckysheet.getLuckysheetfile();
    sheetfile[0].celldata = luckysheet.transToCellData(sheetfile[0].data);
    return sheetfile;
  };

  // 保存按钮
  const onSave = async () => {
    // const sheetfile = readeGetSheetData();
    const sheetData = luckysheet.getSheetData(); // 表数据
    // 生成html
    const html = luckysheet.getRangeHtml({ range: { row: [0, sheetData.length], column: [0, 8] } });

    console.log('保存', html);

    const { id } = await saveSheet({
      data: html,
    });
    let baseUrl = window.location.href;
    baseUrl = baseUrl.replace('/app/printReport', '');
    window.open(`${baseUrl}/app/pdfhtml?id=${id}`);
  };

  return (
    <div className={styles.boxWrap}>
      <Button onClick={() => onUpdata()}>更新数据</Button>
      <Button onClick={onSave}>保存</Button>
      <ExportExcelFileBtn />
      <ExportPdfBtn />
    </div>
  );
};

export default Header;
